sha1 = (str) ->
  # We transform the string into an arraybuffer.
  buffer = new TextEncoder('utf-8').encode(str)
  crypto.subtle.digest('SHA-1', buffer).then (hash) ->
    hex hash

hex = (buffer) ->
  hexCodes = []
  view = new DataView(buffer)
  i = 0
  while i < view.byteLength
    # Using getUint32 reduces the number of iterations needed (we process 4 bytes each time)
    value = view.getUint32(i)
    # toString(16) will give the hex representation of the number without padding
    stringValue = value.toString(16)
    # We use concatenation and slice for padding
    padding = '00000000'
    paddedValue = (padding + stringValue).slice(-padding.length)
    hexCodes.push paddedValue
    i += 4
  # Join all the hex strings into one
  hexCodes.join ''

sign = (ticket, url) =>
   nonce = Math.random().toString(36).substr(2,15)
   timestamp = parseInt(new Date().getTime())
   str = "jsapi_ticket=" + ticket + "&noncestr=" + nonce + "&timestamp=" + timestamp + "&url=" + location.href.split("#",1)[0]
   signature = await sha1(str)
   {
      signature
      timestamp
      nonceStr:nonce
   }


  $.when(
      $.get("//wxticket.xvc.com/ticket.txt?"+(new Date/62e5).toString(36)) # ticket过期时间是7200秒，刷新周期是15分钟，所以获取的ticket最小有效期为7200-15*60-请求响应时间
      $.getScript("//res.wx.qq.com/open/js/jweixin-1.6.0.js")
  ).done ([ticket])=>
      sign(ticket).then (config)->
          jsApiList = "updateTimelineShareData updateAppMessageShareData onMenuShareTimeline onMenuShareAppMessage onMenuShareQQ onMenuShareWeibo onMenuShareQZone".split(' ')

          wx.config Object.assign(config,{
              appId: 'wxab95844927471714'
              jsApiList:jsApiList
          })
          wx.ready ->
            wx.checkJsApi {
              jsApiList
              success: ({checkResult})=>
                page = JSON.parse($("script[type='application/ld+json']").html())

                {headline:title,description:desc} = page

                imgUrl = "https://font.xvc.com/x"
                #img = page.image?.url
                #if img and (img.indexOf('600B5iVR_') < 0)
                #  imgUrl= "https:"+img+"?imageView2/1/w/300/h/300"

                o = {
                  desc
                  imgUrl
                  link:location.href
                  title
                  success:=>
                }
                for [k,v] from Object.entries(checkResult)
                  if v
                    wx[k](o)
                return
            }


